package com.dn.lotte.ui.purchase.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import android.widget.TextView;

import com.dn.lotte.R;
import com.dn.lotte.app.AppConstant;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.bean.HistoryDetailBean;
import com.dn.lotte.bean.PurchaseDetailGameBean;
import com.dn.lotte.bean.PurchaseDetailNumberBean;
import com.dn.lotte.bean.PurchaseDetailTypeBean;
import com.dn.lotte.bean.PurchseDetailTimeBean;
import com.dn.lotte.bean.SelectedBean;
import com.dn.lotte.bean.TimeAndStateBean;
import com.dn.lotte.bean.TimeBean;
import com.dn.lotte.ui.purchase.activity.PurchaseMoreGameActivity;
import com.dn.lotte.ui.purchase.contract.PurchaseNewDetailContract;
import com.dn.lotte.ui.purchase.model.PurchaseNewDetailModel;
import com.dn.lotte.ui.purchase.presenter.PurchaseNewDetailPresenter;
import com.dn.lotte.utils.CommonUtils;
import com.easy.common.base.BaseFragment;
import com.easy.common.commonwidget.RippleView;
import com.google.android.flexbox.FlexboxLayout;
import com.lzy.okgo.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class PurchaseBettingFragment extends BaseFragment<PurchaseNewDetailPresenter, PurchaseNewDetailModel>
        implements PurchaseNewDetailContract.View, RippleView.OnRippleCompleteListener {

    @Bind(R.id.tv_time_number)
    TextView mTimeNumber;
    @Bind(R.id.countRecycler)
    FlexboxLayout mCountRecycler;
    @Bind(R.id.tv_last_time)
    TextView mLastTime;
    @Bind(R.id.money)
    TextView mMoney;
    @Bind(R.id.tablayout)
    TabLayout mTablayout;
    @Bind(R.id.viewpager)
    ViewPager mViewpager;
    @Bind(R.id.moreGame)
    RippleView mMoreGame;
    private String mLid;
    private String mCPName;
    private HttpParams httpParams;

    public static PurchaseBettingFragment getInstance(String id, String cpName) {
        PurchaseBettingFragment purchaseBettingFragment = new PurchaseBettingFragment();
        purchaseBettingFragment.mLid = id;
        purchaseBettingFragment.mCPName = cpName;
        return purchaseBettingFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_purchase_betting;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    private void loadData() {
        showLoading("");
        httpParams = new HttpParams();
        httpParams.put("lid", mLid);
        mPresenter.getHistoryData(httpParams);//获取历史
        mPresenter.getGameTime(httpParams);//获取截至时间
        mPresenter.getMoneyData();//获取余额
        mPresenter.getTypeData(httpParams, mLid);//获取分类、
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        loadData();
        mMoreGame.setOnRippleCompleteListener(this);
    }

    //返回历史开奖
    @Override
    public void returnHistoryData(HistoryDetailBean historyDetailBean) {
        if (historyDetailBean.getResult().equals("1")) {
            List<HistoryDetailBean.TableBean> mHistoryList = historyDetailBean.getTable();
            if (mHistoryList != null && mHistoryList.size() > 0) {
                String number = mHistoryList.get(0).getNumber();
                CommonUtils.showlabel(getActivity(), mCountRecycler, number);
                if (mTimeNumber != null)
                    mTimeNumber.setText(mHistoryList.get(0).getTitle() + "期");
            }
        }
    }

    private CountDownTimer mTimer;

    //返回时间
    @Override
    public void returnGameTime(PurchseDetailTimeBean timeBean) {
        String ordertime = timeBean.getOrdertime();
        String closetime = timeBean.getClosetime();
        int i = Integer.parseInt(ordertime);
        int i2 = Integer.parseInt(closetime);
        i = i - i2;
        if (i == 0) {
            mPresenter.getGameTime(httpParams);//获取截至时间
        } else {
            initTime(i * 1000);
            restart();
        }
    }

    //余额
    @Override
    public void returnMoney(TimeBean timeBean) {
        if (mMoney != null) mMoney.setText("余额:" + timeBean.getMoney() + "元");
    }


    /**
     * 取消倒计时
     */
    public void oncancel() {
        if (mTimer != null) mTimer.cancel();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        oncancel();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 开始倒计时
     */
    public void restart() {
        if (mTimer != null) mTimer.start();
    }

    private void initTime(final long l1) {
        mTimer = new CountDownTimer(l1, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long time = millisUntilFinished / 1000;
                long time1 = time % 60;
                long time2 = (time - time1) / 60 % 60;
                long time3 = ((time - time1) / 60 - time2) / 60;
                mPresenter.getHistoryData(httpParams);//获取历史
                if (mLastTime != null)
                    mLastTime.setText(time3 + (time2 < 10 ? ":0" : ":") + time2 + (time1 < 10 ? ":0" : ":") + time1);
            }

            @Override
            public void onFinish() {
                if (mLastTime != null) mLastTime.setText("本期投注已经截止");
                mPresenter.getGameTime(httpParams);//获取截至时间
            }
        };
    }

    private List<PurchaseDetailTypeBean.TableBean> mTitleList = new ArrayList<>();//玩法

    //玩法
    @Override
    public void returnDetailTypeList(PurchaseDetailTypeBean typeBean) {
        mTitleList = typeBean.getTable();
        if (mTitleList != null && mTitleList.size() > 0) {
            mPresenter.getGameData(httpParams, "DNID" + mLid);
        }
    }

    private MyPagerAdapter mAdapter;
    private ArrayList<Fragment> mFragments;
    private String[] mTitles;

    /**
     * 玩法 分类
     * 思路 ：
     * 第一次加载 显示第一个
     * 以后加载显示选中的
     * 操作： 在P层执行具体逻辑
     *
     * @param gameBean
     */
    @Override
    public void returnDetailGameList(PurchaseDetailGameBean gameBean) {
        /**
         *  創建tablayout 分类
         */
        initTab();
    }

    private void initTab() {
        List<PurchaseDetailGameBean.TableBean> selectGameList = CommonUtils.getSelectGameList("DNID" + mLid);
        mFragments = new ArrayList<>();
        if (selectGameList.size() > 0) {
            mTitles = new String[selectGameList.size()];
            for (int i = 0; i < selectGameList.size(); i++) {
                mTitles[i] = selectGameList.get(i).getTitle();
                if (!isDsOrFs(mTitles[i])) {
                    mFragments.add(PurchaseDSFragment.getInstance(selectGameList.get(i), mLid, mCPName));
                } else
                    mFragments.add(PurchaseFSFragment.getInstance(selectGameList.get(i), mLid, mCPName));
            }
            mAdapter = new MyPagerAdapter(getChildFragmentManager());
            mViewpager.setAdapter(mAdapter);
            mViewpager.setOffscreenPageLimit(1);
            mTablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            mTablayout.setupWithViewPager(mViewpager);

        }
        stopLoading();
    }

    /**
     * 区分单式 复式
     *
     * @param mTitle
     * @return true 复式
     */
    private boolean isDsOrFs(String mTitle) {
        if (mTitle.contains("单式") || mTitle.contains("混选") || mTitle.contains("混合")) {
            return false;
        } else
            return true;
    }

    @Override
    public void returnSelectData(PurchaseDetailGameBean.TableBean gameBean) {

    }

    @Override
    public void returnNumberData(PurchaseDetailNumberBean numberbean) {

    }


    @Override
    public void returnNumberSelectedData(int postion, List<SelectedBean> selectedBeanList) {

    }

    @Override
    public void showLoading(String title) {
        startProgressDialog();
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {

    }

    @Override
    public void onComplete(RippleView rippleView) {
        Bundle bundle = new Bundle();
        bundle.putString("id", mLid);
        startActivity(PurchaseMoreGameActivity.class, bundle);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(EventBusBean<TimeAndStateBean> bean) {
        if (AppConstant.REFRESHBETTINGTAB.equals(bean.getTag())) {
            if (mTablayout != null) mTablayout.removeAllTabs();
            if (mViewpager != null) mViewpager.removeAllViews();
            //更新状态栏
            initTab();
        }
    }

    /**
     * 防止切换bug 将FragmentPagerAdapter 改为FragmentStatePagerAdapter
     */
    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }
}
